// pages/putForwardPrice/putForwardPrice.js
var app = getApp();
var isRepeat = false;

let isSend = false;
let timer = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prohibit: false,
    cards:[],
    money:'',
    allMoney:'',
    id:'',
    index: '',//选中的银行卡数据
    isForward: false,//是否能提现
    isChoose: true, //未选择提现账户
    withdraw_config: '',//提现账户配置
    codeShow: false, //验证弹窗
    accountType: '', //账户类型 1 银行卡，2 微信零钱
    is_phone: false, //是否已授权手机号码
    auth_phone: '', //授权的用户信息
    inputIndex: 0, //聚焦索引
    inputValue: '', //输入验证码value
    inputArr: [], //验证码分割后的数组
    codeShow: false, //验证弹窗
    sms_txt: '',//短信提示
    session_key: '',
    openid: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getOverMomey();
    this.getWithdrawType();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (){
    this.getBankCard();
    isRepeat = false;
  },
  

  // 选择提现账户
  choosecard:function(){
    this.setData({
      prohibit:true
    })
  },

  // 关闭弹窗
  closemodel:function(){
    this.setData({
      prohibit: false
    })
  },
  //全部提现
  all(e){
    var money = e.currentTarget.dataset.money;
    this.setData({
      allMoney: money,
      isForward: this.data.accountType?true:false
    })
  },
  //输入金额
  getMoney(e){
   const value=e.detail.value;
    this.setData({
      allMoney: app.retainDecimal(value),
      isForward: value && this.data.accountType ? true : false
    })
  },
  //选择银行卡
  cardItem:function(e){   
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    this.setData({
      prohibit: false,
      isChoose: false,
      index: index,
      id: id,
      accountType: 1, //账户类型
      isForward: this.data.allMoney? true : false
    })
  },
  // 选择微信
  wxItem() {
    this.setData({
      prohibit: false,
      isChoose: false,
      accountType: 2, //账户类型
      isForward: this.data.allMoney ? true : false
    });
  },

  //余额
  getOverMomey() {
    var that = this;
    app.ajax({
      url: "Partner/User/getPartnerInfo",
      data: {},
      success: function (res) {
        if (res.data.code == 200) {
          that.setData({
            money: res.data.data.account_balance
          })
        }
      }
    })
  },
  // 获取提现账户配置
  getWithdrawType() {
    var that = this;
    app.ajax({
      url: "Common/Common/getWithdrawType",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            withdraw_config: res.data.data
          })
        }
      }
    })
  },

  //合伙人银行卡
  getBankCard(){
    var that = this;
    app.ajax({
      url:"Partner/Bank/getBankList",
      data:{},
      success:function(res){
        if (res.data.code == 1000){
          that.setData({
            cards: res.data.data,
          })
        }
        var accountType = '';
        var chooseItem = '';
        var bankId = '';
        var isChoose = true;
        // 如果有银行卡提现权限，默认选中第一张的银行卡
        if (that.data.withdraw_config.bank.switch && res.data.data.length > 0) {
          bankId = res.data.data[0].bank_id;
          accountType = 1;
          chooseItem = res.data.data[0];
          isChoose = false;
        } else if (that.data.withdraw_config.weixin.switch) {
          accountType = 2;
          isChoose = false;
        }
        that.setData({
          index: chooseItem,
          id: bankId,
          accountType,
          isChoose
        })
      }
    })
  },


  //添加银行卡
  navAddCard() {
    wx.navigateTo({
      url: '../addeditAccount/addeditAccount?type=2',
    })
  },
  // 授权手机号码
  bindPhone(e) {
    if (!this.data.isForward) {
      return false;
    }
    
    console.log('e', e);
    let is_phone = e.detail.iv ? true : false;
    this.setData({
      is_phone
    })
    let auth_detail = e.detail;

    var that = this;
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(that.data.allMoney) || regNeg.test(that.data.allMoney)) {
      if (that.data.allMoney == '') {
        app.showToast('请填写提现金额');
        return false;
      }
      if (that.data.allMoney <= 50) {
        app.showToast('提现金额不能小于50');
        return false;
      }
      if (that.data.allMoney % 10 != 0) {
        app.showToast('提现金额是10的倍数');
        return false;
      }
      if (that.data.money <= 0) {
        app.showToast('您的余额不足');
        return false;
      }

      if (that.data.money - that.data.allMoney < 0) {
        app.showToast('提现金额不能超过余额');
        return false;
      }


    } else {
      app.showToast('请输入正确的金额');
      return false;
    }
    if (is_phone) {
      this.getOpenID(auth_detail);
    }
    if (!is_phone) app.showToast('请授权手机号码，才能提现哦~');
  },
  //获取openid
  getOpenID(auth_detail){
    var that = this;
    var session_key = wx.getStorageSync('session_key')||'';
    var openid = wx.getStorageSync('openid') || '';
    if (session_key){
      that.setData({
        session_key,
        openid
      })
      that.decodePhone(auth_detail);
    }else{
      wx.login({
        success: results => {
          app.ajax({
            url: "Common/Wx/getUserOpenid",
            data: {
              code: results.code
            },
            success: res => {
              if (res.data.code == 1000) {
                that.setData({
                  session_key: res.data.data.session_key,
                  openid: res.data.data.openid
                })
                that.decodePhone(auth_detail);
              }
            }
          })
        },
        fail: e => {
        }
      })
    }
    
  },
  //解码手机号
  decodePhone(auth_detail) {
    console.log('auth_detail', auth_detail);
    app.ajax({
      url: 'Common/Wx/aesPhoneDecrypt',
      data: {
        session_key: this.data.session_key,
        data: auth_detail.encryptedData,
        iv: auth_detail.iv,
      },
      success: (res) => {
        console.log('res>>>>>>>>', res);
        if (res.data.code == 1000) {
          this.setData({
            auth_phone: res.data.data.phoneNumber,
            is_phone: true,
            codeShow: true
          });
          this.sendSms();
        } else {
          this.setData({
            auth_phone: '',
            is_phone: false
          });
          app.showToast(res.data.message);
        }
      }
    });
  },
  // 发送验证码
  sendSms() {
    var that = this;
    if (isSend) return;
    isSend = true;
    app.ajax({
      url: 'Common/Common/sendSms',
      data: { phone: that.data.auth_phone, },
      success: function (res) {
        that.setData({
          sms_txt: res.data.message
        })
        if (res.data.code == 1000) {
          that.setData({
            codeShow: true,
            times: 60
          });
          clearInterval(timer);
          timer = setInterval(() => {
            let times = that.data.times;
            if (times <= 0) {
              clearInterval(timer);
              that.setData({
                times: 0
              });
            } else {
              that.setData({
                times: times - 1
              });
            }
          }, 1000);
        } else {
          //app.showToast(res.data.message);
        }
        isSend = false;
      }
    });
  },
  // 数据验证码
  bindCode(e) {
    var that = this;
    var inputIndex = that.data.inputIndex;
    var value = e.detail.value;
    var inputArr = value.split('');
    console.log('inputArr', inputArr);
    var length = inputArr.length;
    that.setData({
      inputValue: value,
      inputArr: inputArr
    });
    console.log('length', length);
    console.log('inputIndex', inputIndex);
    if (length < 6) {
      that.setData({
        inputIndex: length
      });
    } else {
      that.startCash(value); // 开始提现
    }
  },
  // 关闭手机验证码弹窗
  closeCode() {
    var that = this;
    clearInterval(timer);
    that.setData({
      codeShow: false,
      inputValue: '',
      inputIndex: 0,
      inputArr: []
    });
  },
  // 提现
  newExtract() {
    var that = this;
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(that.data.allMoney) || regNeg.test(that.data.allMoney)) {
      if (that.data.allMoney == '') {
        app.showToast('请填写提现金额');
        return false;
      }
      if (that.data.allMoney <= 50) {
        app.showToast('提现金额不能小于50');
        return false;
      }
      if (that.data.allMoney % 10 != 0) {
        app.showToast('提现金额是10的倍数');
        return false;
      }
      if (that.data.money <= 0) {
        app.showToast('您的余额不足');
        return false;
      }

      if (that.data.money - that.data.allMoney < 0) {
        app.showToast('提现金额不能超过余额');
        return false;
      }


    } else {
      app.showToast('请输入正确的金额');
      return false;
    }

    this.setData({
      auth_phone: that.data.accountType == 1 ? that.data.index.phone_whole : that.data.auth_phone,
      codeShow: true
    });
    this.sendSms();
  },
  // 开始提现
  startCash(sms_code) {
    var that = this;
    if (isRepeat) {
      return;
    }
    isRepeat = true;

    app.ajax({
      url: "Partner/Achievement/launchApplication",
      data: {
        account_type: that.data.accountType,
        bank_id: that.data.accountType == 1 ? that.data.id:'',
        wx_openid: that.data.accountType == 2 ? that.data.openid : '',
        money: that.data.allMoney,
        code: sms_code,
        phone: that.data.auth_phone
      },
      success: function (res) {
        isRepeat = false;
        if (res.data.code == 1000) {
          // 关闭发送验证码弹窗
          that.setData({
            codeShow: false
          });
          app.showToast(res.data.message)
          setTimeout(function () {
            wx.navigateBack({
              delta: 1,
            })
          }, 1000);
        } else {
          app.showToast(res.data.message)
        }
      }
    })

  },
})